package com.jinly.ryder.log.web;


import com.jinly.ryder.common.auth.annotation.Auth;
import com.jinly.ryder.common.auth.annotation.AuthParam;
import com.jinly.ryder.common.auth.model.AuthRole;
import com.jinly.ryder.common.auth.model.AuthType;
import com.jinly.ryder.common.utils.SpringContextUtil;
import com.jinly.ryder.log.service.LogSearchService;
import com.jinly.ryder.log.service.model.ContextQuery;
import com.jinly.ryder.log.service.model.LogContent;
import com.jinly.ryder.log.service.model.SearchQuery;
import com.jinly.ryder.log.service.model.SearchResult;
import com.jinly.ryder.manage.service.AppInfoService;
import com.jinly.ryder.manage.service.model.AppLogType;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("log/search")
@RequiredArgsConstructor
public class LogSearchController {
    private final AppInfoService appInfoService;

    /**
     * 日志搜索
     *
     * @param query
     * @return
     */
    @GetMapping()
    @Auth(type = AuthType.APP, role = AuthRole.DEVELOPER, value = "#{appName}")
    public SearchResult search(@AuthParam("appName") SearchQuery query) {
        LogSearchService logSearchService = getLogSearchService(query.getAppName());
        if (logSearchService != null) {
            return logSearchService.search(query);
        }
        return new SearchResult();
    }

    /**
     * 日志上下文
     *
     * @param query
     * @return
     */
    @GetMapping("context")
    @Auth(type = AuthType.APP, role = AuthRole.DEVELOPER, value = "#{appName}")
    public List<LogContent> searchContext(@AuthParam("appName") ContextQuery query) {
        LogSearchService logSearchService = getLogSearchService(query.getAppName());
        if (logSearchService != null) {
            return logSearchService.logContextList(query);
        }
        return List.of();
    }

    private LogSearchService getLogSearchService(String appName) {
        AppLogType appLogType = appInfoService.getAppInfo(appName).getLogType();
        return (LogSearchService) SpringContextUtil.getBean(appLogType.name().toLowerCase() + "LogSearchService");
    }
}
